<template>
  <view class="flex-col">
    <navbar title="意见反馈"></navbar>
    <view class="block">
      <view class="sub-title">问题和意见</view>
      <view class="flex-col" style="height: 288rpx;background-color: #fff;padding: 30rpx">
        <textarea class="input-opinion" maxlength="200" placeholder="请填写你遇到的问题和建议，感谢你的支持~"
                  placeholder-style="color:#CCCCCC" v-model="opinion"/>
        <text class="option-length-text">{{ opinion.length + '/200' }}</text>
      </view>
    </view>
    <view class="custom-btn primary submit" @click="submit">确定</view>
  </view>
</template>

<script>
import Navbar from "../../components/navbar";
import {commonApi, reportApi} from '@/api'

export default {
  components: {Navbar},
  data() {
    return {
      opinion: '',//意见
      photo: [],//图片
      max: 3
    }
  },
  methods: {
    async submit() {
      if (!this.opinion || this.opinion.length === 0) {
        uni.showToast({
          title: '请输入问题和意见',
          duration: 2000,
          icon: 'none'
        });
        return
      }

      let imgs = []
      uni.showLoading({
        title: '加载中...',
      })
      if (this.photo && this.photo.length > 0) {
        imgs = await this.uploadImages(this.photo)
      }
      await this.uploadData(this.opinion, imgs)
      setTimeout(() => {
        uni.hideLoading()
        uni.navigateBack()
      }, 1000)
    },
    async uploadImages(photo) {
      const res = await commonApi.getUploadToken()
      const {
        token,
        imgHost,
        url
      } = res.data.data

      return new Promise((resolve, reject) => {
        const images = [];
        for (let i = 0; i < photo.length; i++) {
          const filePath = photo[i].img;
          const key = Math.random().toString(36).substr(2); //生成一个随机字符串的文件名

          uni.uploadFile({
            url, //华东地区上传地址
            filePath,
            name: 'file',
            formData: {
              token, //刚刚获取的上传凭证
              'key': 'error_report/' + key //这里是为文件设置上传后的文件名
            },
            success: async (uploadFileRes) => {
              console.log(uploadFileRes.data)
              const data = JSON.parse(uploadFileRes.data.trim())
              const img = imgHost + data.key
              console.log('data', data)
              images.push({img});
              if (images.length === photo.length) {
                resolve(images)
              }
            },
            fail: (e) => {
              console.log('hsf', 'uploadFile===error:' + JSON.stringify(e));
              reject(e)
            }
          })
        }
      })
    },
    async uploadData(content, photo = []) {
      try {
        const data = {
          content
        }
        photo.map((item, i) => {
          data['img' + i] = item.img
        })
        await reportApi.create(data)
        uni.showToast({
          title: '提交成功，感谢您的反馈！',
          icon: 'success',
          duration: 2000
        });
      } catch (e) {
        console.log(e)
        uni.showToast({
          title: e.data.msg,
          icon: 'none',
          duration: 2000
        });
      }
    },
    addImgAction() {
      const count = this.max - this.photo.length
      console.log(count)
      uni.chooseImage({
        count: count,
        sizeType: 'compressed',
        success: async (result) => {
          for (let i = 0; i < result.tempFilePaths.length; i++) {
            const img = result.tempFilePaths[i];
            this.photo.push({img});
          }
        }
      })
    },
  }

}
</script>

<style lang="scss">
page {
  background-color: #f7f7f7;
}

.block {
  padding-top: 40rpx;

  &.white {
    background-color: #fff;
  }
}

.sub-title {
  font-size: 30rpx;
  color: #000000;
  font-weight: bold;
  margin-left: 30rpx;
  margin-bottom: 30rpx
}

.input-opinion {
  font-size: 28rpx;
  width: 100%;
  flex: 1;

}

.option-length-text {
  color: #CCCCCC;
  font-size: 30rpx;
  align-self: end;
}

.submit {
  margin: 50rpx 94rpx;
}

</style>
